import { useRouter } from 'next/navigation';
import Cookies  from 'js-cookie';
import React, { useEffect, useRef, useState } from 'react'
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import {
  Form,
  Input,
  Button,
  message
} from 'antd';

import ServiceClient  from '@/app/api/utils/serviceClient';
export type ILoginProps = {
    params: any
}
const sApi = new ServiceClient()

const Login = () => {
  
  const [form] = Form.useForm();

  const router = useRouter();

  const onFinish = async ()=>{
  
    sApi.login(form.getFieldsValue()).then(res=>{
      console.log("res===",res)
        if(res.data.code===200){
            //设置cookie
            Cookies.set("token",res.data.access_token,{expires:100,path:'/'})
            Cookies.set("user",res.data.user_id+"_"+res.data.username,{expires:100,path:'/'})
            localStorage.setItem("user_id",res.data.user_id)
            localStorage.setItem("user_name",res.data.username)
            message.success('登陆成功！');
            //跳转首页
            router.push('/')
        }else{
           message.warning(res.data.message);
        }
    })
  } 

  const onFinishFailed =()=>{
    message.error('登录失败!');
  }

    return (
        <>
          <Form
            form={form}
            className='flex flex-col justify-between'
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
             autoComplete="off"
          >
            <Form.Item label="用户名"
            name="username" rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input  prefix={<UserOutlined />} placeholder="输入用户名"/>
            </Form.Item>
            <Form.Item label="密码" style={{marginLeft:"15px"}}
             name="password" rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input type='password' prefix={<LockOutlined />} placeholder="输入密码" />
            </Form.Item> 
            <Form.Item>
              <Button type='primary' className=' w-full text-center' htmlType="submit">登录</Button>
            </Form.Item> 
          </Form>
  
        </>
      );
}
export default Login